<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
</head>
<body>
    <div>
        用户名：<input type="text" id="username">
        密码： <input type="password" id="password">
        <button id="login">登录</button>
    </div>

    <script>
        var login = document.getElementById('login');
        login.onclick = function () {
            var username = document.getElementById('username').value;
            var password = document.getElementById('password').value;
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/admin/login');
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send('username=' + username + '&password=' + password);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var result = JSON.parse(xhr.responseText);
                    if (result.code == 200) {
                        // uid保存到cookie中
                        document.cookie = 'uid=' + result.uid;
                        // token保存到cookie中
                        document.cookie = 'token=' + result.token;
                        localStorage.setItem('uid', result.uid);
                        localStorage.setItem('username', result.username);
                        localStorage.setItem('token', result.token);
                        location.href = '/admin/index';
                    } else {
                        console.log(result.message);
                    }
                }
            }
        }
    </script>
</body>
</html>